#pragma once


#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"
#include "LockGuard.hpp"
namespace dictionary
{
    const std::string defaultpath = "./Dictionary.txt";
    const std::string sep = ": ";
    class Dictionary
    {   //创建字典对象后，加载整个字典到内存中
        private:
        bool Load()
        {
            //是从文件中向内存中读
            std::ifstream in(_dictionary_conf_path);

            if(!in.is_open())
            {
                LOG(FATAL,"open the dictionary%s error\n",_dictionary_conf_path.c_str());
                return false;
            }

            std::string line;
            while(std::getline(in,line))
            {
                if(line.empty())continue;
                auto pos = line.find(sep);//从下标为0的位置开始找
                if(pos == std::string:: npos)continue;

                //substr的第二个参数是长度
                std::string word = line.substr(0,pos);//左闭右开
                if(word.empty()) continue;
                std::string result = line.substr(pos+sep.size());
                if(result.empty()) continue;
                

                LOG(DEBUG,"load a pair to memory:%s,%s",word.c_str(),result.c_str());

                _dictionary.insert(std::make_pair(word,result));
            }
            in.close();
            LOG(DEBUG,"load the dictionary %s success\n",_dictionary_conf_path.c_str());
            return true;
        }
        public:
        Dictionary(const std::string& path = defaultpath):_dictionary_conf_path(path)
        {
            Load();
        }
        std::string Translate(const std::string& word,bool& ok)
        {
            ok = true;
            auto iter = _dictionary.find(word);
            if(iter == _dictionary.end())
            {
                ok = false;
                return "未找到";
            }
            return iter->second;
        }
        ~Dictionary()
        {
        }


        private:
        std::unordered_map<std::string,std::string> _dictionary;
        std::string _dictionary_conf_path; 
    };



}